package cn.monkey.transport.netty.server.codec.protocol.tcp.mqtt;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.util.function.BiPredicate;

public interface MqttServerProtocolPredicate extends BiPredicate<Channel, ByteBuf> {
    MqttServerProtocolPredicate INSTANCE = new MqttServerProtocolPredicate() {
    };

    @Override
    default boolean test(Channel channel, ByteBuf byteBuf) {
        byte[] array = byteBuf.array();
        boolean hasMqttFirstWord = false;
        StringBuilder sb = new StringBuilder();
        for (byte b : array) {
            if ("MQTT".contentEquals(sb) || "MQIsdp".contentEquals(sb)) {
                return true;
            }
            if (hasMqttFirstWord) {
                // MQIsdp
                if (b != 'Q' && b != 'T' && b != 'I' && b != 's' & b != 'd' & b != 'p') {
                    return false;
                }
                sb.append((char) b);
            }
            if (b == 'M') {
                hasMqttFirstWord = true;
                sb.append((char) b);
            }
        }
        return false;
    }
}
